import os, json, yaml
from baseFunction import loadEyeTrackerData, outputProbData, crateXlsFile, outputPatternToXlwt
from baseFunction import crateGazeProbData, crateGazeTrackProbData
from miningFuntion import Classical_Sequential_Pattern
from miningFuntion import PrefixSpan_for_Sequential_Pattern, getTotalSupp, getRarity



if __name__ == "__main__":
    with open('config.yaml') as config_file:
        try:
            config = yaml.load(config_file, Loader=yaml.SafeLoader)
            ROOT_PATH, OUTPUT_PATH = config['ROOT_PATH'], config["OUTPUT_PATH"]
        except:
            print("There is no config.yaml, or no information in config.yaml")
            exit(0)

        """ 创建用于保存结果的xlm文件 """
        sheet_name_list = ["高分生共有行为模式", "低分生行为模式", "高分生行为模式"]
        workbook_1, sheet_dict_1 = crateXlsFile(OUTPUT_PATH + "GAZE_POINT/", sheet_name_list)
        workbook_2, sheet_dict_2 = crateXlsFile(OUTPUT_PATH + "GAZE_TRACK/", sheet_name_list)

        Pattern_Summary_Dict_point, Pattern_Summary_Dict_track = {}, {}
        student_type_dict = {}
        """ 将学生分为"高分组"和"低分组" """
        for student_type in os.listdir(ROOT_PATH):  # "data-correct", "data-incorrect"
            print("start mining patterns of", ROOT_PATH + student_type, "students \n")
            dir_path = ROOT_PATH + student_type + "/"

            """ 将原始数据加工处理成概率事件 """
            GAZE_POINT_DICT, GAZE_TRACK_DICT = {}, {}
            for file_name in os.listdir(dir_path):
                file_path = dir_path + file_name
                user_name = str(file_name.split(".txt")[0])

                """ 记录学生类型 """
                if student_type not in student_type_dict.keys():
                    student_type_dict[student_type] = []
                student_type_dict[student_type].append(user_name)

                """ 读取文本内容 """
                raw_data_dict = loadEyeTrackerData(file_path)
                gaze_prob_data = crateGazeProbData(raw_data_dict)
                GAZE_POINT_DICT[user_name] = gaze_prob_data; print(gaze_prob_data)
                gazetrack_prob_data = crateGazeTrackProbData(raw_data_dict)
                GAZE_TRACK_DICT[user_name] = gazetrack_prob_data; print(gazetrack_prob_data)

                """ 并将事件描述保存至本地 """
                output_dir_path_1 = OUTPUT_PATH + "gaze_point/"
                outputProbData(output_dir_path_1, file_name, gaze_prob_data)
                output_dir_path_2 = OUTPUT_PATH + "gaze_track/"
                outputProbData(output_dir_path_2, file_name, gazetrack_prob_data)

                """ 挖掘算法 """
                Pattern_Summary_Dict_point[user_name], Pattern_Summary_Dict_track[user_name] = {}, {}
                PrefixSpan_for_Sequential_Pattern([], gaze_prob_data, [], Pattern_Summary_Dict_point[user_name])
                PrefixSpan_for_Sequential_Pattern([], gazetrack_prob_data, [], Pattern_Summary_Dict_track[user_name])

        """ 计算计算所有高分学生的公共行为模式的支持度 """
        Pattern_this_type_Dict_1 = getTotalSupp(Pattern_Summary_Dict_point, user_ids=student_type_dict["data-correct"], user_type="correct—students")
        Pattern_this_type_Dict_2 = getTotalSupp(Pattern_Summary_Dict_track, user_ids=student_type_dict["data-correct"], user_type="correct—students")
        """ 保存公共行为模式到 avg supports of correct students' patterns """
        outputPatternToXlwt(sheet_dict_1["高分生共有行为模式"], Pattern_this_type_Dict_1, user_list = list(Pattern_this_type_Dict_1.keys()), sort_by="support")
        outputPatternToXlwt(sheet_dict_2["高分生共有行为模式"], Pattern_this_type_Dict_2, user_list = list(Pattern_this_type_Dict_2.keys()), sort_by="support")
        # getTotalSupp(Pattern_Summary_Dict_point)
        # getTotalSupp(Pattern_Summary_Dict_track)

        """ 计算所有学生的模式稀疏性，找出每个低分学生最具代表性的行为模式 """
        getRarity(Pattern_Summary_Dict_point, user_ids=list(Pattern_Summary_Dict_point.keys()), user_type="total")
        outputPatternToXlwt(sheet_dict_1["低分生行为模式"], Pattern_Summary_Dict_point, user_list=student_type_dict["data-incorrect"], sort_by="typical")   # 序列模式挖掘的结果输出到xls文件中
        outputPatternToXlwt(sheet_dict_1["高分生行为模式"], Pattern_Summary_Dict_point, user_list=student_type_dict["data-correct"], sort_by="typical")   # 序列模式挖掘的结果输出到xls文件中

        getRarity(Pattern_Summary_Dict_track, user_ids=list(Pattern_Summary_Dict_track.keys()), user_type="total")
        outputPatternToXlwt(sheet_dict_2["低分生行为模式"], Pattern_Summary_Dict_track, user_list=student_type_dict["data-incorrect"], sort_by="typical")   # 序列模式挖掘的结果输出到xls文件中
        outputPatternToXlwt(sheet_dict_2["高分生行为模式"], Pattern_Summary_Dict_track, user_list=student_type_dict["data-correct"], sort_by="typical")   # 序列模式挖掘的结果输出到xls文件中

        workbook_1.save(OUTPUT_PATH + "Sequential_Patterns_for_GazePoint.xls")
        workbook_2.save(OUTPUT_PATH + "Sequential_Patterns_for_GazeTrack.xls")
